package com.stlm2.core.yun;

import com.stlm2.core.AppConfig;
import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

/**
 * 回拨电话
 *
 */
public class Call {
	
	/**
	 * 开始通话
	 * @param from
	 * @param to
	 * @return
	 */
	public static String start(String from, String to){
		if(StringUtils.isBlank(from) || StringUtils.isBlank(to))
			return null;
		JSONObject json = new JSONObject();
		json.put("from", from);
		json.put("to", to);
		json.put("customerSerNum", AppConfig.CUSTOMER_PHONE);
		json.put("fromSerNum", AppConfig.CUSTOMER_PHONE);

		String url = Core.BASE_SUBACCOUNT_URL + "/Calls/Callback";
		String result = Core.post(true, url, json.toString());
		if(StringUtils.isBlank(result))
			return null;
		
		json = new JSONObject(result);
		if(Core.SUCC_CODE.equals(json.getString("statusCode"))){
			String callSid = json.getJSONObject("CallBack").getString("callSid");
			return callSid;
		}
		return null;
	}

	/**
	 * 取消通话
	 * @param sid
	 * @return
	 */
	public static boolean cancel(String sid){
		if(StringUtils.isBlank(sid))
			return false;

		String url = Core.BASE_SUBACCOUNT_URL + "/Calls/CallCancel";
		JSONObject json = new JSONObject();
		json.put("appId", Core.APP_ID);
		json.put("callSid", sid);
		json.put("type", "1");//设置被叫应答前可以挂断电话

		String result = Core.post(true, url, json.toString());
		if(StringUtils.isBlank(result))
			return false;

		json = new JSONObject(result);
		return Core.SUCC_CODE.equals(json.getString("statusCode"));
	}
}